package com.hnevc.music;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;

public class Main2Activity extends AppCompatActivity {

    private Button btn;
    private ListView listView;
    private ContentResolver resolver;
    private ArrayList<Music> musicList;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        initView();
        initEvent();
    }

    private void initEvent() {
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                readMusic();
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(Main2Activity.this, MainActivity.class);

                intent.putExtra("musicPath", musicList.get(position).getMusicPath());

                startActivity(intent);
            }
        });

    }

    private void initView() {
        btn = findViewById(R.id.btn);
        listView = findViewById(R.id.misic_list);

    }

    private void readMusic() {

        resolver = getContentResolver();
        Cursor cursor = resolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
                , new String[]{MediaStore.Audio.Media._ID
                        , MediaStore.Audio.Media.TITLE
                        , MediaStore.Audio.Media.ARTIST,MediaStore.Audio.Media.DATA}
                , null, null, null);

        musicList = new ArrayList();

        while (cursor.moveToNext()) {
            Music music = new Music();
            music.setId(cursor.getString(0));
            music.setMusicName(cursor.getString(1));
            music.setSinger(cursor.getString(2));
            music.setMusicPath(cursor.getString(3));
            musicList.add(music);
        }
        listView.setAdapter(new MyAdapter(Main2Activity.this, musicList));
    }


}
